package com.rahms.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rahms.common.constant.MessageConstant;
import com.rahms.common.result.R;
import com.rahms.pojo.dto.AuthLoginDTO;
import com.rahms.pojo.dto.AuthRegisterDTO;
import com.rahms.pojo.entity.User;
import com.rahms.server.service.UserService;
import com.rahms.server.utils.JwtTokenUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
@Tag(name = "认证管理", description = "用户注册、登录、退出等认证相关接口")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired(required = false)
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "新用户注册接口，支持家属和管理员注册")
    public R<User> register(@RequestBody AuthRegisterDTO dto) {
        // 使用缓存查询用户是否存在
        User existingUser = userService.getUserByUsername(dto.getUsername());
        if (existingUser != null) {
            return R.error(MessageConstant.USERNAME_EXISTS);
        }
        User user = new User();
        user.setUsername(dto.getUsername());
        user.setPassword(passwordEncoder != null ? passwordEncoder.encode(dto.getPassword()) : dto.getPassword());
        user.setRealName(dto.getRealName());
        user.setPhone(dto.getPhone());
        user.setRole(dto.getRole());
        user.setStatus(1);
        boolean saved = userService.save(user);
        return saved ? R.success(user).add("message", MessageConstant.REGISTER_SUCCESS) : R.error(MessageConstant.SAVE_FAILED);
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录接口，返回用户信息和JWT Token")
    public R<Map<String, Object>> login(@RequestBody AuthLoginDTO dto) {
        // 使用缓存查询用户
        User user = userService.getUserByUsername(dto.getUsername());
        if (user == null) {
            return R.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        boolean matches = passwordEncoder != null ? passwordEncoder.matches(dto.getPassword(), user.getPassword()) : dto.getPassword().equals(user.getPassword());
        if (!matches) {
            return R.error(MessageConstant.PASSWORD_ERROR);
        }
        
        // 生成JWT令牌
        String token = jwtTokenUtil.generateToken(user.getUserId(), user.getUsername(), user.getPhone(), user.getRealName());
        
        Map<String, Object> result = new HashMap<>();
        result.put("user", user);
        result.put("token", token);
        
        return R.success(result).add("message", MessageConstant.LOGIN_SUCCESS);
    }
}


